package blog;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

//负责用户登录的功能
public class UserLoginAction implements Action {
    @Override
    public void run() {
        User user = new User();

        System.out.print("用户登录>");
        System.out.println();

        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入用户名称(不支持中文)>");
        String username = scanner.nextLine();
        System.out.print("请输入密码>");
        String password = scanner.nextLine();

        try (Connection connection = DBUtil.getConnection()) {
            String sql = "select id,username,nickname from users where username = ? and password = ? ";
                try (PreparedStatement preparedStatement=connection.prepareStatement(sql)){
                        preparedStatement.setString(1,username);
                        preparedStatement.setString(2,password);
                        try (ResultSet resultSet=preparedStatement.executeQuery()){
                            //因为username是unique的，所以查找的过程是，要不返回1行数据，要不返回0行数据
                            if(resultSet.next()){
                                int id=resultSet.getInt(1);
                                String nickname=resultSet.getString(2);
                                user.id=id;
                                user.username=username;
                                user.nickname=nickname;

                                //进行用户登录
                                User.login(user);
                            }else {
                                System.out.println("用户名或者密码错误，重新登录！");
                            }
                        }
                    }
                } catch (SQLException e) {
            System.out.println("错误：" + e.getMessage());
        }
    }
}
